﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;



/// <summary>
/// 角色视角控制
/// </summary>
public class CharacterView
{
    private CharacterController character;

    private Camera camera;
    private float minAngle;
    private float maxAngle;

    private float activeAngle;
    private bool openMoudle;



    public void InputView()
    {
        if(openMoudle)
        {
            RotateCharacterHori();
            RotateCharacterVect();
        }
    }



    private void RotateCharacterHori()
    {
        var mouseX = Input.GetAxis("Mouse X");
        character.transform.Rotate(0,mouseX,0);
    }

    private void RotateCharacterVect()
    {
        var mouseY = Input.GetAxis("Mouse Y");
        mouseY = GetLerpAngleFromActiveAngle(mouseY);

        camera.transform.Rotate(-mouseY,0,0);
    }

    private float GetLerpAngleFromActiveAngle(float angle)
    {
        activeAngle += angle;

        if(activeAngle > maxAngle)
        {
            activeAngle = maxAngle;
            if(angle > 0)
                return 0;
        }
        else if(activeAngle<minAngle)
        {
            activeAngle = minAngle;
            if(angle<0)
                return 0;
        }

        return angle;
    }



    private Camera GetCameraFormName(string name)
    {
        if(name!="")
        {
            var cameraObj = GameObject.Find(name);

            if(cameraObj)
            {
                var cameraOnIt = cameraObj.GetComponent<Camera>();
                if(cameraOnIt)
                    return cameraOnIt;
            }
        }

        return Camera.main;
    }

    public CharacterView(CharacterController character,PlayerWatchProperties watchProperties)
    {
        this.camera = GetCameraFormName(watchProperties.CameraName);

        minAngle = watchProperties.MinAngle;
        maxAngle = watchProperties.MaxAngle;
        openMoudle = watchProperties.ActiveViewControl;

        this.character = character;
    }
}
